package org.slf4j.impl;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

public class XtraTinyLoggerFactory implements ILoggerFactory {
	private ConcurrentHashMap<String, XtraTinyLogger> map = new ConcurrentHashMap<>();
	private CopyOnWriteArraySet<XtraTinyLoggerAppender> appenders;
	private XtraTinyLoggerConfigurator conf = new XtraTinyLoggerConfigurator();

	private class XtraTinyLoggerShutdownHookThread extends Thread {
		public void run() {
			for (XtraTinyLoggerAppender appender : appenders) {
				appender.close();
			}
		}
	}

	public XtraTinyLoggerFactory() {
		Runtime.getRuntime().addShutdownHook(
				new XtraTinyLoggerShutdownHookThread());
		appenders = new CopyOnWriteArraySet<XtraTinyLoggerAppender>();
	}

	public Logger getLogger(String name) {
		XtraTinyLogger logger = map.get(name);
		if (logger == null) {
			Set<XtraTinyLoggerAppender> appenders = conf.getAppenders(name);
			this.appenders.addAll(appenders);
			logger = new XtraTinyLogger(name, appenders);
			logger.setLevel(conf.getLoggerLevel(name));
			logger.setFormat(conf.getLoggerFormat(name));
			XtraTinyLogger anotherLoggerInstance = map
					.putIfAbsent(name, logger);
			if (anotherLoggerInstance != null) {
				logger = anotherLoggerInstance;
			}
		}
		return logger;
	}
}
